package com.tjh.hive_data_compare.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by tjh.
 * Date: 2021/5/21
 **/
public class HiveUtil {
    private static final Logger logger = LogManager.getLogger(HiveUtil.class);
    private Connection connection = null;

    public void init(String serverUrl, String userName, String passWord, String dbName) throws Exception {
        try {
            Class.forName("org.apache.hive.jdbc.HiveDriver");
            connection = DriverManager.getConnection("jdbc:hive2://" + serverUrl + ":10000/" + dbName, userName, passWord);
        } catch (SQLException | ClassNotFoundException e) {
            System.out.println("创建Hive连接失败" + e);
            throw e;
        }
    }

    public void destory() throws Exception {
        if (connection != null) {
            connection.close();
        }
    }


    public List<String> showDatabases() {
        List<String> dbList = new ArrayList<>();
        String sql = "show databases";
        try (Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(sql)) {
            while (rs.next()) {
                System.out.println("查询到数据库：{}" + rs.getString(1));
                dbList.add(rs.getString(1));
            }
        } catch (SQLException e) {
            System.out.println("创建数据库出错" + e);
        }


        return dbList;
    }

    /**
     * 查询所有表
     */
    public List<String> showTables() {
        String sql = "show tables";
        List<String> tableList = new ArrayList<>();

        System.out.println("查询所有表，脚本：{}" + sql);
        try (Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(sql)) {
            while (rs.next()) {
                tableList.add(rs.getString(1));
            }
        } catch (SQLException e) {
            System.out.println("查询所有表出错" + e);
        }

        return tableList;
    }


    /**
     * 查数量
     */
    public int count(String tableName) {
        int result = 0;
        String sql = "select count(1) from  " + tableName;
        System.out.println("查数量，脚本：{}" + sql);
        try (Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(sql)) {
            while (rs.next()) {
                result = rs.getInt(1);
            }
        } catch (SQLException e) {
            System.out.println("查数量出错" + e);
        }

        return result;
    }
}
